package org.bot.plugin.data.event;

import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author 沧月
 * @create 0022 2023/9/22 13:06
 * @description <遍历节点数据>
 */

@Component
@EventName("迭代器")
public class DataForEach implements Events {
    @Override
    public Object exec(FlowNode note, DataStorage data) {
        String dataIndex = note.getDataIndex();
        Object o = data.get(dataIndex);
        if (o == null) {
            return null;
        }

        //设置遍历索引初始值
        if (note.getExtendAttr() == null) {
            note.setExtendAttr(0);
        }

        if (o instanceof Collection) {
            Collection coll = (Collection) o;
            if (coll.isEmpty()) {
                return null;
            }
            int index = 0;
            if ((Integer) note.getExtendAttr() >= coll.size()) {
                return null;
            }
            for (Object value : coll) {
                if ((Integer) note.getExtendAttr() == index) {
                    note.setExtendAttr(((Integer) note.getExtendAttr()) + 1);
                    return value;
                }
                index++;
            }
        }
        return null;
    }
}
